<?php

namespace app;

// 应用请求对象类
use think\response\Json;
use think\Validate;

class Request extends \think\Request
{
    /**
     * 验证请求参数
     *
     * @param  array  $rules
     * @param  array  $messages
     * @return array|mixed
     */
    public function validate(array $rules, array $messages = [])
    {
        $validator = new Validate;
        $validator->rule($rules);

        if ($messages) {
            $validator->message($messages);
        }

        $validator->failException(true)->check($this->param());

        return $this->param(array_keys($rules));
    }

    /**
     * 从请求头中获取 bearer token
     *
     * @return string|null
     */
    public function bearerToken(): ?string
    {
        $header = $this->header('Authorization', '');

        $position = strrpos($header, 'Bearer ');

        if ($position === false) {
            return null;
        }

        $header = substr($header, $position + 7);

        return strpos($header, ',') !== false ? strstr($header, ',', true) : $header;
    }
}
